package com.qianfeng.android.baoman;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.adapter.TopicArticleAdapter;
import com.qianfeng.android.baoman.model.Article;
import com.qianfeng.android.baoman.model.Other;
import com.qianfeng.android.baoman.model.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class UserDetailActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ListView>, RadioGroup.OnCheckedChangeListener {

    private LinearLayout load_layout;
    private PullToRefreshListView refreshListView;
    private ListView listView;
    //设置加载延迟时间
    private Handler handler = new Handler();

    private int pageCount;
    private User user;
    private ImageView defaultImage;

    private Other other;

    private List<Article> articleList;
    private TopicArticleAdapter adapter;
    private TextView textCoins;
    private RadioGroup rg;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_detail);
        pageCount = 1;
        setActionBarTitle("Ta的暴走");
        setFunctionVisible(true);
        ImageButton imageButton = (ImageButton) findViewById(R.id.action_function);
        imageButton.setImageResource(R.drawable.my_center_setting_btn);
        //加载数据时显示
        load_layout = (LinearLayout) findViewById(R.id.load_layout);
        //
        defaultImage = (ImageView) findViewById(R.id.activity_user_detail_default);

        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");
        loadUserData(Constants.getOthersDetail(user.getId()));


        refreshListView =
                (PullToRefreshListView) findViewById(R.id.activity_see_other_pullRoRefreshList);
        listView = refreshListView.getRefreshableView();
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        Drawable drawable = getResources().getDrawable(R.drawable.arrow_down);
        refreshListView.setLoadingDrawable(drawable);
        // 设置加载中的标题
        refreshListView.setRefreshingLabel("加载...");
        // 设置“松开”提醒
        refreshListView.setReleaseLabel("松开可以刷新");
        refreshListView.setOnRefreshListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_user_detail_header, null, false);
        listView.addHeaderView(view);
        setViewHeader(view);

        other = new Other();
        articleList = new ArrayList<>();

        adapter = new TopicArticleAdapter(this, articleList);

        listView.setAdapter(adapter);
        listView = refreshListView.getRefreshableView();

        loadArticleData(Constants.getOtherCreation(user.getId(), 1));
    }

    private void setViewHeader(View view) {
        final View view1 = view.findViewById(R.id.item_user_detail_view1);
        final View view2 = view.findViewById(R.id.item_user_detail_view2);
        TextView textView = (TextView) view.findViewById(R.id.item_user_detail_userName);
        textView.setText(user.getLogin());

        textCoins = (TextView) view.findViewById(R.id.item_user_detail_coins_count);

        rg = (RadioGroup) view.findViewById(R.id.item_user_detail_shenzuo);
        if (rg != null) {
            rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    int count = group.getChildCount();
                    int position = -1;
                    for (int i = 0; i < count; i++) {
                        View view = group.getChildAt(i);
                        if (view instanceof RadioButton) {
                            RadioButton rb = (RadioButton) view;
                            if (rb.isChecked()) {
                                position = i;
                                break;
                            }
                        }
                    }
                    if (position != -1) {
                        switch (position) {
                            case 0:
                                view1.setVisibility(View.VISIBLE);
                                view2.setVisibility(View.INVISIBLE);
                                defaultImage.setImageResource(R.drawable.no_article_img);
                                break;
                            case 1:
                                view1.setVisibility(View.INVISIBLE);
                                view2.setVisibility(View.VISIBLE);
                                defaultImage.setImageResource(R.drawable.no_pubarticle_img);
                                break;
                        }
                    }
                }
            });
            View rgChildAt = rg.getChildAt(0);
            if (rgChildAt instanceof RadioButton) {
                RadioButton rb = (RadioButton) rgChildAt;
                rb.setChecked(true);
            }
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pageCount = 1;
                loadArticleData(Constants.getOtherCreation(user.getId(), pageCount));
                refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }, 1000);
    }


    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pageCount++;
                loadArticleData(Constants.getOtherCreation(user.getId(), pageCount));
            }
        }, 1000);
    }


    private void loadUserData(String url) {
        load_layout.setVisibility(View.VISIBLE);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        String result = objectResponseInfo.result;
                        try {
                            refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                            refreshListView.onRefreshComplete();
                            JSONObject object = new JSONObject(result);
                            other.parseJSON(object);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    textCoins.setText(Integer.toString(other.getSalary()));
                                }
                            });
                            load_layout.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(UserDetailActivity.this, "网络问题", Toast.LENGTH_SHORT).show();
                        refreshListView.setVisibility(View.GONE);
                        load_layout.setVisibility(View.GONE);
                        refreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                        pageCount = 1;
                    }
                });
    }


    private void loadArticleData(String url) {
        load_layout.setVisibility(View.VISIBLE);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        String result = objectResponseInfo.result;
                        try {
                            refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                            refreshListView.onRefreshComplete();
                            JSONObject object = new JSONObject(result);
                            int total_pages = object.getInt("total_pages");
                            if (pageCount > total_pages) {
                                load_layout.setVisibility(View.GONE);
                                return;
                            }
                            JSONArray articles = object.getJSONArray("articles");
                            for (int i = 0; i < articles.length(); i++) {
                                JSONObject jsonObject = articles.getJSONObject(i);
                                Article article = new Article();
                                article.parseJSON(jsonObject);
                                articleList.add(article);
                            }
                            if (articleList.size() == 0) {
                                defaultImage.setVisibility(View.VISIBLE);
                                return;
                            } else {
                                defaultImage.setVisibility(View.GONE);
                                int childCount = rg.getChildCount();
                                for (int i = 0; i < childCount; i++) {
                                    View view = rg.getChildAt(i);
                                    if (view instanceof RadioButton) {
                                        RadioButton rb = (RadioButton) view;
                                        rb.setText("(" + articleList.size() + ")");
                                    }
                                }
                            }
                            adapter.notifyDataSetChanged();
                            Log.i("UserDetailActivity", other.toString());
                            load_layout.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(UserDetailActivity.this, "网络问题", Toast.LENGTH_SHORT).show();
                        refreshListView.setVisibility(View.GONE);
                        load_layout.setVisibility(View.GONE);
                        refreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                        pageCount = 1;
                    }
                });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

    }
}